package com.wuxiaofan.service;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuxiaofan.entity.Dict;
import com.wuxiaofan.entity.vo.DictEeVo;
import com.wuxiaofan.listen.DictReadListener;
import com.wuxiaofan.mapper.DictMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class DictService {
    @Resource
    private DictMapper dictTMapper;

    public List<Dict> findByParentId(Long parentId){
        Map paraMap = new HashMap<>();
        paraMap.put("parent_id",parentId);
        List<Dict> list = dictTMapper.selectByMap(paraMap);
        list.forEach(dict->{
            int count = countByParentId(dict.getParentId());
            if(count>0){
                dict.setHasChildren(true);
            }else{
                dict.setHasChildren(false);
            }
        });
        return list;
    }

    public int countByParentId(Long parentId){
        QueryWrapper<Dict> wrapper = new QueryWrapper();
        wrapper.eq("parent_id",parentId);
        int count = dictTMapper.selectCount(wrapper);
        return count;
    }

    public void exportData(HttpServletResponse response) throws Exception{
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("数据字典","UTF-8");
        response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");
        List<Dict> dictList = dictTMapper.selectList(null);
        List<DictEeVo> dictEeVoList = new ArrayList<>();
        dictList.forEach(dict->{
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);
            dictEeVo.setId(dict.getId()+"");
            dictEeVo.setParentId(dict.getParentId()+"");
            dictEeVo.setValue(dict.getValue()+"");
            if(dict.getDeleteStatus().equals("0")){
                dictEeVo.setDeleteStatus("不可用");
            }else{
                dictEeVo.setDeleteStatus("可用");
            }
            dictEeVoList.add(dictEeVo);
        });
        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(outputStream,DictEeVo.class).sheet("字典信息").doWrite(dictEeVoList);
    }

    public void importData(InputStream inputStream) {
        log.info("上传");
        List<DictEeVo> dictEeVoList = EasyExcel.read(inputStream, DictEeVo.class, new DictReadListener()).sheet().doReadSync();
        log.info("dictEeVoList:{}",dictEeVoList);
    }
}
